package com.siyoumi.app.modules.wx_qr.admin;

import com.siyoumi.app.entity.WxQr;
import com.siyoumi.app.service.WxQrService;
import com.siyoumi.component.XApp;
import com.siyoumi.component.http.InputData;
import com.siyoumi.controller.AdminApiController;
import com.siyoumi.util.XReturn;
import com.siyoumi.util.XStr;
import com.siyoumi.validator.XValidator;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

@RestController
@RequestMapping("/xadmin/wp_qr/wp_qr__edit")
public class wp_qr__edit
        extends AdminApiController {
    @GetMapping()
    public XReturn index() {
        setPageTitle("小程序码-编辑");

        WxQrService app = WxQrService.getBean();

        Map<String, Object> data = new HashMap<>();
        data.put("is_hyaline", 0);
        if (isAdminEdit()) {
            WxQr entity = app.loadEntity(getID());

            HashMap<String, Object> dataAppend = new LinkedHashMap<>();
            dataAppend.put("id", entity.getKey());
            dataAppend.put("qr_img", XApp.fileUrl(entity.getWxqr_info()));

            //合并
            data = entity.toMap();
            data.putAll(dataAppend);
        }
        getR().setData("data", data);


        return getR();
    }


    @Transactional
    @PostMapping("/save")
    public XReturn save(@Validated() WxQr entity, BindingResult result) {
        //统一验证
        XValidator.getResult(result);
        //自定交验证
        if (!XStr.startsWith(entity.getWxqr_path(), "pages")) {
            result.addError(XValidator.getErr("wxqr_path", "page内容错误【pages/index/index】"));
        }
        XValidator.getResult(result);

        WxQrService app = WxQrService.getBean();

        List<String> ignoreField = new ArrayList<>();
        if (isAdminEdit()) {
        }

        InputData inputData = InputData.fromRequest();
        inputData.putAll(entity.toMap());
        return app.saveEntity(inputData, true, ignoreField);
    }
}
